package life.cqq.jwt.filter;

import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

@WebFilter(filterName = "globalFilter", urlPatterns = "/*")
public class GlobalFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // Do nothing
    }

    @Override
    public void destroy() {
        // Do nothing
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 1. 跨域
        allowCrossDomain(request, response);
        if (HttpMethod.OPTIONS.matches(request.getMethod())) {
            response.setStatus(HttpStatus.OK.value());
            return;
        }
        // 2. 编码
        utf8Encoding(request, response);
        // 3. 放行
        filterChain.doFilter(servletRequest, servletResponse);
    }

    /**
     * 允许C端发起跨域请求
     *
     * @param request
     * @param response
     */
    private void allowCrossDomain(HttpServletRequest request, HttpServletResponse response) {
        // 1. 当前端配置withCredentials=true时, 后端配置Access-Control-Allow-Origin不能为*, 必须是相应地址
        // 2. 当前端配置withCredentials=true时, 后端需配置Access-Control-Allow-Credentials
        // 3. 当前端配置请求头时, 后端需要配置Access-Control-Allow-Headers为对应的请求头集合

        String[] allowOrigin = new String[] {
          request.getHeader("Origin"),
        };
        response.setHeader("Access-Control-Allow-Origin", String.join(",", allowOrigin));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods",
                "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS,TRACE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers",
                "Content-Type, X-Requested-With, accept, Origin, Authorization," +
                        "Access-Control-Request-Method, Access-Control-Request-Headers");
    }

    /**
     * UTF8编码
     *
     * @param request
     * @param response
     */
    private void utf8Encoding(HttpServletRequest request, HttpServletResponse response)
            throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        response.setHeader("Content-type", "text/html;charset=UTF-8");
    }
}